package com.edooteach.tencent.accessor.impl;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.http.annotation.Rao;
import com.demo2do.core.wechat.entity.cfg.Config;
import com.demo2do.core.wechat.entity.token.Token;
import com.demo2do.core.wechat.rao.wechat.WechatTokenRao;
import com.demo2do.core.wechat.utils.WechatUtils;
import com.edooteach.tencent.accessor.WeappTokenAccessor;

/**
 * 
 * @author mohanlan
 *
 */
@Component("weappTokenAccessor")
public class WeappTokenAccessorImpl implements WeappTokenAccessor {
	
	private static final Logger logger = LoggerFactory.getLogger(WeappTokenAccessor.class);
    
    @Rao
    private WechatTokenRao wechatTokenRao;
    
    private Config config;
    
    /**
     * 
     * @param appid
     * @param appsecret
     */
    @Autowired
    public void config(@Value("#{weapp['appid']}") String appid, @Value("#{weapp['appsecret']}") String appsecret) {
        this.config = new Config(appid, appsecret);
    }

	/*
	 * (non-Javadoc)
	 * @see com.edooteach.tencent.accessor.WeappTokenAccessor#requestAccessToken()
	 */
	public Token requestAccessToken() {
		
		logger.trace("#requestAccessToken - Request global access_token for appid[{}] and appsecret[{}]", this.config.getAppid(), this.config.getAppsecret());
		
		// 1. call rao to get access token
        HttpResult httpResult = wechatTokenRao.getAccessToken(config.getAppid(), config.getAppsecret());
        
        if(WechatUtils.isValid(httpResult)) {  // this is a valid response
            
            // 2. get response data
            Map<String, Object> response = httpResult.describe();
            
            String accessToken = (String) response.get("access_token");
            Integer expireTime = (Integer) response.get("expires_in");
            
            return new Token(accessToken, expireTime);
        
        }
        
        throw WechatUtils.toBusinessException(httpResult);
	}
	
}
